package job.relevance.anchor_weight;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class RLV_AW_Offline {

    public static void main(String[] args) throws IOException {
        String recordFile = "/home/renp/a3/raw.feature.global.fix";
        String awFile = "/home/renp/a3/Global.aw";
        int N = 13;
        int m = 5;
        
        Map<String, String> map = loadAw(awFile);
        BufferedReader br = new BufferedReader(new FileReader(recordFile));
        BufferedWriter bw = new BufferedWriter(new FileWriter(recordFile + ".aw"));
        int lineNo = 0;
        String tag = "";
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            lineNo++;
            if (lineNo % N == 1) {
                tag = line.trim();
            }
            if (lineNo % N == m) {
                String anchor = map.get(tag);
                if (anchor == null) {
                    anchor = "";
                }
                if (line.contains("\2")) {
                    bw.write(line.substring(0, (line + "\2").indexOf("\2")));
                    bw.write(anchor);
                }
            } else {
                bw.write(line);
            }
            bw.newLine();
        }
        bw.flush();
        bw.close();
        br.close();
    }

    private static Map<String, String> loadAw(String awFile) throws IOException {
        Map<String, String> ret = new HashMap<String, String>();
        
        BufferedReader br = new BufferedReader(new FileReader(awFile));
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            int pos = line.indexOf("\2");
            String tag = line.substring(0, pos).trim();
            String anchor = line.substring(pos);
            ret.put(tag, anchor);
        }
        br.close();
        
        return ret;
    }
    
}
